Page({
  data: {
    loading: false,
    submitting: false,
    reminderId: null,
    members: [],
    selectedMemberId: null,
    selectedMemberIndex: 0,
    selectedMemberName: '',
    title: '',
    content: '',
    type: 'medication', // 默认为用药提醒
    typeIndex: 0, // 默认选中第一个类型
    typeLabel: '用药提醒', // 默认类型标签
    placeholderText: '请输入药品名称、用量等', // 默认提示文本
    date: '',
    time: '',
    repeatType: 'once', // 默认为一次性提醒
    repeatTypeIndex: 0, // 默认选中第一个重复类型
    repeatTypeLabel: '一次性', // 默认重复类型标签
    repeatOptions: [
      { value: 'once', label: '一次性' },
      { value: 'daily', label: '每天' },
      { value: 'weekly', label: '每周' },
      { value: 'monthly', label: '每月' }
    ],
    weekdays: [
      { value: '周一', checked: false },
      { value: '周二', checked: false },
      { value: '周三', checked: false },
      { value: '周四', checked: false },
      { value: '周五', checked: false },
      { value: '周六', checked: false },
      { value: '周日', checked: false }
    ],
    showWeekdaySelector: false,
    reminderTypes: [
      { value: 'medication', label: '用药提醒' },
      { value: 'checkup', label: '体检提醒' },
      { value: 'exercise', label: '运动提醒' },
      { value: 'diet', label: '饮食提醒' },
      { value: 'other', label: '其他提醒' }
    ]
  },

  onLoad: function(options) {
    // 获取提醒ID
    if (options.id) {
      this.setData({
        reminderId: parseInt(options.id)
      });
      
      // 加载提醒详情
      this.loadReminderDetail(options.id);
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      wx.navigateBack();
    }
    
    // 加载家庭成员数据
    this.loadMembers();
  },
  
  formatNumber: function(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },
  
  // 更新提示文本
  updatePlaceholderText: function() {
    let placeholderText = '请输入提醒详情';
    
    if (this.data.type === 'medication') {
      placeholderText = '请输入药品名称、用量等';
    } else if (this.data.type === 'checkup') {
      placeholderText = '请输入体检地点、注意事项等';
    }
    
    this.setData({ placeholderText });
  },
  
  loadReminderDetail: function(id) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    wx.request({
      url: `http://localhost:3000/api/reminders/${id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const reminder = res.data.data.reminder;
          
          // 处理重复类型和值
          let weekdays = [...this.data.weekdays];
          if (reminder.repeat_type === 'weekly' && reminder.repeat_value) {
            const selectedDays = reminder.repeat_value.split(',');
            weekdays = weekdays.map(day => {
              return {
                ...day,
                checked: selectedDays.includes(day.value)
              };
            });
          }
          
          // 找到类型索引
          const typeIndex = this.data.reminderTypes.findIndex(t => t.value === reminder.type);
          const typeLabel = typeIndex >= 0 ? this.data.reminderTypes[typeIndex].label : '用药提醒';
          
          // 找到重复类型索引
          const repeatTypeIndex = this.data.repeatOptions.findIndex(o => o.value === reminder.repeat_type);
          const repeatTypeLabel = repeatTypeIndex >= 0 ? this.data.repeatOptions[repeatTypeIndex].label : '一次性';
          
          // 设置表单数据
          this.setData({
            selectedMemberId: reminder.member_id,
            title: reminder.title,
            content: reminder.content || '',
            type: reminder.type,
            typeIndex: typeIndex >= 0 ? typeIndex : 0,
            typeLabel: typeLabel,
            date: reminder.remind_date || '',
            time: reminder.remind_time,
            repeatType: reminder.repeat_type,
            repeatTypeIndex: repeatTypeIndex >= 0 ? repeatTypeIndex : 0,
            repeatTypeLabel: repeatTypeLabel,
            weekdays: weekdays,
            showWeekdaySelector: reminder.repeat_type === 'weekly',
            loading: false
          }, () => {
            // 更新提示文本
            this.updatePlaceholderText();
          });
        } else {
          console.error('获取提醒详情失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取提醒详情失败',
            icon: 'none'
          });
          wx.navigateBack();
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        wx.navigateBack();
      }
    });
  },
  
  loadMembers: function() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const members = res.data.data.members || [];
          this.setData({
            members: members,
            loading: false
          });
          
          // 如果已经有选择的成员ID，找到对应的名称和索引
          if (this.data.selectedMemberId) {
            const selectedMember = members.find(m => m.id === this.data.selectedMemberId);
            const selectedMemberIndex = members.findIndex(m => m.id === this.data.selectedMemberId);
            
            if (selectedMember) {
              this.setData({
                selectedMemberName: selectedMember.name,
                selectedMemberIndex: selectedMemberIndex >= 0 ? selectedMemberIndex : 0
              });
            }
          }
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  onMemberChange: function(e) {
    const index = parseInt(e.detail.value);
    const member = this.data.members[index];
    
    if (member) {
      this.setData({
        selectedMemberId: member.id,
        selectedMemberIndex: index,
        selectedMemberName: member.name
      });
    }
  },
  
  onTitleInput: function(e) {
    this.setData({
      title: e.detail.value
    });
  },
  
  onContentInput: function(e) {
    this.setData({
      content: e.detail.value
    });
  },
  
  onTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    const type = this.data.reminderTypes[index];
    
    if (type) {
      this.setData({
        type: type.value,
        typeIndex: index,
        typeLabel: type.label
      }, () => {
        // 更新提示文本
        this.updatePlaceholderText();
      });
    }
  },
  
  onDateChange: function(e) {
    this.setData({
      date: e.detail.value
    });
  },
  
  onTimeChange: function(e) {
    this.setData({
      time: e.detail.value
    });
  },
  
  onRepeatTypeChange: function(e) {
    const index = parseInt(e.detail.value);
    const repeatOption = this.data.repeatOptions[index];
    
    if (repeatOption) {
      this.setData({
        repeatType: repeatOption.value,
        repeatTypeIndex: index,
        repeatTypeLabel: repeatOption.label,
        showWeekdaySelector: repeatOption.value === 'weekly'
      });
    }
  },
  
  onWeekdayChange: function(e) {
    const index = e.currentTarget.dataset.index;
    const weekdays = this.data.weekdays;
    weekdays[index].checked = !weekdays[index].checked;
    
    this.setData({
      weekdays: weekdays
    });
  },
  
  submitForm: function() {
    // 表单验证
    if (!this.data.selectedMemberId) {
      wx.showToast({
        title: '请选择家庭成员',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.title.trim()) {
      wx.showToast({
        title: '请输入提醒标题',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.time) {
      wx.showToast({
        title: '请选择提醒时间',
        icon: 'none'
      });
      return;
    }
    
    // 如果是每周重复，至少选择一天
    if (this.data.repeatType === 'weekly') {
      const hasSelectedDay = this.data.weekdays.some(day => day.checked);
      if (!hasSelectedDay) {
        wx.showToast({
          title: '请至少选择一天',
          icon: 'none'
        });
        return;
      }
    }
    
    // 处理重复值
    let repeatValue = null;
    if (this.data.repeatType === 'weekly') {
      const selectedDays = this.data.weekdays
        .filter(day => day.checked)
        .map(day => day.value);
      repeatValue = selectedDays.join(',');
    }
    
    // 组装请求数据
    const reminderData = {
      member_id: this.data.selectedMemberId,
      title: this.data.title,
      content: this.data.content,
      type: this.data.type,
      remind_time: this.data.time,
      repeat_type: this.data.repeatType,
      repeat_value: repeatValue
    };
    
    // 一次性提醒需要日期
    if (this.data.repeatType === 'once') {
      reminderData.remind_date = this.data.date;
    }
    
    // 提交表单
    this.updateReminder(reminderData);
  },
  
  updateReminder: function(reminderData) {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ submitting: true });
    
    wx.request({
      url: `http://localhost:3000/api/reminders/${this.data.reminderId}`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: reminderData,
      success: (res) => {
        this.setData({ submitting: false });
        
        if (res.data.success) {
          wx.showToast({
            title: '更新提醒成功',
            icon: 'success'
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          console.error('更新提醒失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '更新提醒失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ submitting: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },
  
  cancel: function() {
    wx.navigateBack();
  }
}) 